package com.lucifer.treasure.enchant.effect;

import com.mojang.serialization.MapCodec;
import com.mojang.serialization.codecs.RecordCodecBuilder;
import net.fabricmc.fabric.api.entity.event.v1.ServerLivingEntityEvents;
import net.minecraft.enchantment.EnchantmentEffectContext;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.enchantment.EnchantmentLevelBasedValue;
import net.minecraft.enchantment.effect.EnchantmentEntityEffect;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.EquipmentSlot;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.damage.DamageSource;
import net.minecraft.entity.passive.BeeEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.particle.ParticleTypes;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.sound.SoundCategory;
import net.minecraft.sound.SoundEvents;
import net.minecraft.util.math.Vec3d;

public record BeekeeperEnchantmentEffect(EnchantmentLevelBasedValue protection) implements EnchantmentEntityEffect {
    public static final MapCodec<BeekeeperEnchantmentEffect> CODEC = RecordCodecBuilder.mapCodec(instance ->
            instance.group(
                    EnchantmentLevelBasedValue.CODEC.fieldOf("protection").forGetter(BeekeeperEnchantmentEffect::protection)
            ).apply(instance, BeekeeperEnchantmentEffect::new)
    );

    public static void initialize() {
        // 监听伤害事件来减少特定生物的伤害
        ServerLivingEntityEvents.ALLOW_DAMAGE.register((entity, source, amount) -> {
            return !shouldBlockDamage(entity, source);
        });

        // 监听实体目标改变事件（虽然Fabric没有直接的事件，我们用tick事件来处理蜜蜂的仇视）
        // 这里我们主要通过伤害事件来处理
    }

    /**
     * 检查是否应该阻止伤害
     */
    private static boolean shouldBlockDamage(LivingEntity victim, DamageSource source) {
        int level = getBeekeeperLevel(victim);
        if (level <= 0) {
            return false;
        }

        Entity attacker = source.getSource();
        if (attacker == null) {
            return false;
        }

        EntityType<?> attackerType = attacker.getType();

        // 1级保护：蜜蜂、羊驼口水
        if (level >= 1) {
            if (attackerType == EntityType.BEE ||
                    attackerType == EntityType.LLAMA_SPIT) {

                // 如果是蜜蜂攻击，额外处理蜜蜂的仇视状态
                if (attacker instanceof BeeEntity bee && victim instanceof PlayerEntity) {
                    pacifyBee(bee);
                }

                // 播放保护音效
                playProtectionEffects(victim, attacker);
                return true; // 阻止伤害
            }
        }

        // 2级保护：额外保护幻翼
        if (level >= 2) {
            if (attackerType == EntityType.PHANTOM) {
                playProtectionEffects(victim, attacker);
                return true; // 阻止伤害
            }
        }

        return false;
    }

    /**
     * 安抚蜜蜂，移除其攻击性
     */
    private static void pacifyBee(BeeEntity bee) {
        // 移除蜜蜂的愤怒状态
        bee.setAngerTime(0);
        bee.setAngryAt(null);

        // 移除攻击目标
        bee.setTarget(null);

        // 如果可能的话，设置蜜蜂为非攻击性
        try {
            // 尝试设置蜜蜂的攻击性为false
            if (bee.hasAngerTime()) {
                bee.setAngerTime(0);
            }
        } catch (Exception e) {
            // 如果方法不存在或有问题，忽略错误
        }
    }

    /**
     * 播放保护效果（音效和粒子）
     */
    private static void playProtectionEffects(LivingEntity victim, Entity attacker) {
        // 播放保护音效
        victim.getWorld().playSound(null, victim.getX(), victim.getY(), victim.getZ(),
                SoundEvents.BLOCK_ENCHANTMENT_TABLE_USE, SoundCategory.PLAYERS,
                0.5f, 1.2f + victim.getWorld().getRandom().nextFloat() * 0.3f);

        // 生成保护粒子效果
        if (victim.getWorld() instanceof ServerWorld serverWorld) {
            // 蜂蜜色粒子效果（金色）
            serverWorld.spawnParticles(ParticleTypes.HAPPY_VILLAGER,
                    victim.getX(), victim.getY() + 1.0, victim.getZ(),
                    8, // 粒子数量
                    0.5, 0.5, 0.5, // 扩散范围
                    0.1 // 初始速度
            );

            // 在攻击者和受害者之间生成阻挡效果
            double midX = (victim.getX() + attacker.getX()) / 2;
            double midY = (victim.getY() + attacker.getY()) / 2 + 0.5;
            double midZ = (victim.getZ() + attacker.getZ()) / 2;

            serverWorld.spawnParticles(ParticleTypes.ENCHANT,
                    midX, midY, midZ,
                    12, // 粒子数量
                    0.3, 0.3, 0.3, // 扩散范围
                    0.05 // 初始速度
            );

            // 蜜蜂相关的特殊效果
            if (attacker.getType() == EntityType.BEE) {
                serverWorld.spawnParticles(ParticleTypes.DRIPPING_HONEY,
                        victim.getX(), victim.getY() + 0.5, victim.getZ(),
                        5, // 粒子数量
                        0.3, 0.1, 0.3, // 扩散范围
                        0.02 // 初始速度
                );
            }
        }
    }

    /**
     * 获取实体的Beekeeper附魔等级（只检查头盔）
     */
    private static int getBeekeeperLevel(LivingEntity entity) {
        // 只检查头盔
        ItemStack helmet = entity.getEquippedStack(EquipmentSlot.HEAD);
        if (helmet.isEmpty()) {
            return 0;
        }

        var enchantments = EnchantmentHelper.getEnchantments(helmet);
        int level = 0;

        for (var entry : enchantments.getEnchantments()) {
            if (entry.getKey().isPresent()) {
                String enchantmentId = entry.getKey().get().getValue().toString();
                if (enchantmentId.equals("lucifer_treasure:beekeeper")) {
                    level = Math.max(level, enchantments.getLevel(entry));
                }
            }
        }

        return level;
    }

    @Override
    public void apply(ServerWorld world, int level, EnchantmentEffectContext context, Entity target, Vec3d pos) {
        // 主要逻辑在事件监听器中处理
        // 这里可以添加持续的保护效果
        if (target instanceof LivingEntity living) {
            // 添加微妙的蜂蜜粒子效果表示附魔存在
            if (world.getRandom().nextInt(100) < 2) { // 2%概率
                world.spawnParticles(ParticleTypes.DRIPPING_HONEY,
                        target.getX(), target.getY() + 0.1, target.getZ(),
                        1, 0.1, 0.1, 0.1, 0.01);
            }
        }
    }

    @Override
    public MapCodec<? extends EnchantmentEntityEffect> getCodec() {
        return CODEC;
    }
} 